<?php

namespace app\service;


use app\model\TaskModel;
use app\tool\SingletonTrait;
use teamones\filter\Enforcer;

class TaskV2Service
{
    use SingletonTrait;

    /**
     * 获取与我相关的统计数量
     *  通过前端传过来的code+筛选条件筛选与我相关的数据
     * @param string $fields
     * @param string $responseFormatType
     * @param string $code 前端权限CODE【我创建的,我分配的,我负责的,我参与的】
     * @param array $rangTime ["range_time":[开始时间,结束时间]]
     * @param array $filter 筛选条件 【项目,集,环节工序,搜索....】
     * @param array $page
     * @param int $limit
     * @return array ["count":"数量，最多不超过100个"]
     */
    public function getTaskMemberCount(string $fields, string $responseFormatType = 'count', string $code = '', array $rangTime = [0, 0], array $filter = [], array $page = [0, 100], int $limit = 100): array
    {
        $returnData = [
            'count' => 0,
            'list' => [],
            'group_by_list' => []
        ];
        if (empty($fields)) {
            $fields = "distinct task.id";
        }
        $extendFilter['range_time'] = $rangTime;
        $taskMemberModel = TaskModel::field($fields)
            ->join('entity', 'entity.id = task.entity_id', 'LEFT')
            ->join('module', 'entity.module_id = module.id', 'LEFT');
        if (empty($filter['task.id'])) {
            $taskMemberModel->join("task_member", 'task_member.task_id = task.id');
        }
        $needTaskStepType = [
            TaskModel::STEP_TYPE_STEP,
            TaskModel::STEP_TYPE_STANDARD_REVIEW,
            TaskModel::STEP_TYPE_STANDARD_MEETING,
            TaskModel::STEP_TYPE_STANDARD_MAKE_TO_DO,
            TaskModel::STEP_TYPE_WORK_ORDER_TO_DO,
            TaskModel::STEP_TYPE_ENTITY_TO_DO,
            TaskModel::STEP_TYPE_TODO,
            TaskModel::STEP_TYPE_PERSON,
        ];
        $taskMemberModel = $taskMemberModel
            ->whereIn('task.step_type', $needTaskStepType)
            ->where('task.tenant_id', request()->getTenantId());
        $taskMemberModel = $this->getFilterByCode($taskMemberModel, $code, $extendFilter);
        if ($responseFormatType == 'count' && $limit > 0) {
            $taskMemberModel->limit($limit);
        }
        if ($responseFormatType == 'list') {
            $taskMemberModel->page(...$page);
        }
        // 集筛选
        if (!empty($filter['initial_episode_code_list'])) {
            $initialEpisodeCodeList = $filter['initial_episode_code_list'];
            $taskMemberModel->whereRaw(EntityService::getInstance()->initialEpisodeCodeSql($initialEpisodeCodeList, "initial_episode_code", "showings_number"));
        }
        // 任务状态
        if (!empty($filter['task_status'])) {
            $taskStatus = $filter['task_status'];
            $taskMemberModel->whereRaw("get_json_string(task.`json`, '$.task_status') IN ($taskStatus)");
        }
        // 任务名
        if (!empty($filter['task_name'])) {
            $taskName = $filter['task_name'];
            $taskMemberModel->whereRaw("((task.name like '%$taskName%') or entity.name like '%$taskName%' or entity.code like '%$taskName%')");
        }
        if (!empty($filter)) {
            unset($filter['initial_episode_code_list']);
            unset($filter['task_status']);
            unset($filter['task_name']);
            $taskMemberModel->where(Enforcer::parseWhere($filter));
        }
        $taskMemberModel = $taskMemberModel->order('task.id desc')->select();
        if (empty($taskMemberModel->toArray())) {
            return $returnData;
        }
        $taskMemberList = $taskMemberModel->toArray();
        if ($responseFormatType == 'count') {
            $returnData['count'] = count($taskMemberList);
        }
        if ($responseFormatType == 'list') {
            $returnData['list'] = $taskMemberList;
        }
        return $returnData;
    }


    /**
     * 通过code 找到对应 where 条件
     * @param $dbr
     * @param string $code
     * @param $extendFilter
     * @return mixed
     */
    public function getFilterByCode($dbr, string $code, $extendFilter)
    {
        if (empty($code)) {
            return $dbr;
        }
        $finalStatusId = StatusService::getInstance()->byCode('final')['id'];
        $remakeStatusId = StatusService::getInstance()->byCode('remake')['id'];
        $closedStatusId = StatusService::getInstance()->byCode('closed')['id'];
        $feedbackStatusId = StatusService::getInstance()->byCode('feedback')['id'];
        $submittedStatusId = StatusService::getInstance()->byCode('submitted')['id'];
        $notStartedStatusId = StatusService::getInstance()->byCode('not_started')['id'];
        $waitForPartyAReviewStatusId = StatusService::getInstance()->byCode('wait_for_party_a_review')['id'];
        // 我创建的
        if ($code == 'createdTask') {
            $rangeTime = $extendFilter['range_time'];
            if (!empty($rangeTime[0]) && !empty($rangeTime[1])) {
                $dbr->whereBetweenTime('task.created', $rangeTime[0], $rangeTime[1]);
            }
            $dbr->where('task.created_by', request()->getSaasUserId());
        }
        // 我分配的
        if ($code == 'assignedTask') {
            $dbr->where('task.assignee_producer', request()->getSaasUserId());
        }
        // 我负责的
        if ($code == 'responsibleTask') {
            $dbr->where('task.assignee', request()->getSaasUserId());
        }
        // 我参与的
        if ($code == 'participatedTask') {
            $dbr->where('task_member.partner', request()->getSaasUserId());
        }
        // 全部任务
        if ($code == 'allTask') {
            $dbr->where('task_member.partner', request()->getSaasUserId());
        }
        // 返修中任务
        if ($code == 'underRepairTask') {
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->whereRaw("get_json_string(task.`json`, '$.task_status') in ($remakeStatusId,$feedbackStatusId)");
        }
        // 审核中任务
        if ($code == 'underReviewTask') {
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->whereRaw("get_json_string(task.`json`, '$.task_status') in ($submittedStatusId,$waitForPartyAReviewStatusId)");
        }
        // 逾期任务
        if ($code == 'abnormalTask') {
            $dayRange = get_day_range_unix();
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->whereRaw("get_json_string(task.`json`, '$.task_status') not in ($closedStatusId,$finalStatusId)")
                ->where('task.plan_delivery_time', '<', $dayRange['sdate']);
        }
        // 工单任务
        if ($code == 'workOrderTask') {
            $dayRange = get_day_range_unix();
            $dbr->join('task_work_order', 'task_work_order.task_id = task_member.task_id')
                ->where('task_member.partner', request()->getSaasUserId())
                ->where('task_work_order.status', 0)
                ->whereRaw("get_json_string(task.`json`, '$.task_status') <> $finalStatusId")
                ->whereRaw('(task.plan_delivery_time < ' . $dayRange['edate'] . ' or task.plan_end_time < ' . $dayRange['edate'] . ')');
        }
        // 今日应交付任务
        if ($code == 'dueToday') {
            $dayRange = get_day_range_unix();
            $dbr->where('task_member.partner', request()->getSaasUserId())
//                ->whereIn('task.step_type', ['step', 'standard_make_to_do'])
                ->whereRaw("get_json_string(task.`json`, '$.task_status') not in ($closedStatusId,$finalStatusId)")
                ->whereBetweenTime('task.plan_delivery_time', $dayRange['sdate'], $dayRange['edate']);
        }
        // 今日应完成任务
        if ($code == 'completedToday') {
            $dayRange = get_day_range_unix();
            $dbr->where('task_member.partner', request()->getSaasUserId())
//                ->whereIn('task.step_type', ['step', 'standard_make_to_do'])
                ->whereRaw("get_json_string(task.`json`, '$.task_status') not in ($closedStatusId,$finalStatusId)")
                ->whereBetweenTime('task.plan_end_time', $dayRange['sdate'], $dayRange['edate']);
        }
        // 生产任务
        if ($code == 'produceTask') {
            $dayRange = get_day_range_unix();
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->whereIn('task.step_type', ['step', 'standard_make_to_do'])
                ->whereRaw("get_json_string(task.`json`, '$.task_status') not in ($closedStatusId,$finalStatusId)")
                ->whereRaw('(task.plan_delivery_time < ' . $dayRange['edate'] . ' or task.plan_end_time < ' . $dayRange['edate'] . ')');
        }
        // 标准会议
        if ($code == 'standardMeet') {
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->where('task.step_type', 'standard_meeting')
                ->whereRaw("get_json_string(task.`json`, '$.task_status') = $notStartedStatusId");
        }
        // 标准审核
        if ($code == 'standardExamine') {
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->where('task.step_type', 'standard_review')
                ->whereRaw("get_json_string(task.`json`, '$.task_status') = $notStartedStatusId");
        }
        // 个人待办
        if ($code == 'personalTodo') {
            $dbr->where('task_member.partner', request()->getSaasUserId())
                ->where('task.step_type', 'person')
                ->whereRaw("get_json_string(task.`json`, '$.task_status') = $notStartedStatusId");
        }
        return $dbr;
    }

}
